<?php
namespace frontend\controllers;

use Yii;
use yii\db\Query;
use frontend\models\record\PostCategory;
use frontend\models\record\PostGroupAudit;
use common\utils\HtmlSpider;
use yii\helpers\Html;

/**
 * Ucenter controller
 */
class UcenterController extends BaseController
{

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionCreategroup()
    {
        $category_list = (new Query())->select('*')
            ->from(PostCategory::tableName())
            ->createCommand(Yii::$app->db)
            ->queryAll();
        return $this->render('create_group', [
            'category_list' => $category_list,
        ]);
    }

    public function actionAjaxcreategroup()
    {
        $model = new PostGroupAudit();
        $model->load(Yii::$app->request->post(), '');
        $error_array = $model->createPostGroup();
        return json_encode($error_array);
    }

    public function actionPostspide() {
        $rule_txt = $_POST['ta_rule'];
        $json_rule = json_decode($rule_txt, true);
        $spider = new HtmlSpider();
        $result = $spider->load($json_rule);
        $txt = json_encode($result);
        $txt = Html::encode($txt);
//        $rule_txt = $this->httpGet('https://www.baidu.com');
        return $txt;
    }

    private function httpGet($url) {
        $opts = array(
            'http'=>array(
                'method'=>"GET",
                'timeout'=>3,
            )
        );
        return file_get_contents($url, false, stream_context_create($opts));
    }
}
